const express = require('express')
const path = require('path')
const app = express()

//设置静态资源目录为public文件夹
app.use(express.static(path.join(__dirname, '/public')));

//引入路由
const users = require('./router/admin/users')
const message = require('./router/api/message')
const article = require('./router/api/article')
const classArt = require('./router/api/class')
const image = require('./router/api/image')

const vueShowArt = require('./router/vueShow/article')
const vueShowClass = require('./router/vueShow/class')
const upload = require('./router/api/upload')


//引入token的生成和验证
const { verifyToken } = require('./jwt')

//发送post请求所必要的
const bodyParser = require('body-parser')

//这是在文件上传限制在20mb，数值可以随便改
app.use(bodyParser.json({ limit: '20mb' }));
app.use(bodyParser.urlencoded({ limit: '20mb', extended: true }));

//连接数据库
const mongoose = require('mongoose');
const dbName = 'blog';
// const url = `mongodb://localhost:27017/${dbName}`;
const url = `mongodb://root:hEMpp8yKY8WT8GZ8@101.43.176.216:27017/`;
// const url = `mongodb://101.43.176.216:27017/${dbName}`;
mongoose.connect(url)
  .then(() => { console.log("数据库连接成功") })
  .catch((err) => { console.log(err) })

// app.use((req, res, next) => {
//   console.log(req.url)
//   // 创建一个正则，匹配以/vueShow开头的路由
//   const regex = /^\/vueShow/;
//   // 这里把登陆和注册请求去掉了，其他的路由请求都需要进行token校验 
//   if (req.url == '/admin/login' || req.url == '/admin/reg' || regex.test(req.url) || req.url == '/index') {
//     next();
//   } else {
//     //获取请求头携带的token
//     // console.log(req.headers)
//     let token = req.headers.authorization;
//     //验证token是否过期
//     let result = verifyToken(token);
//     // 如果验证通过就next，否则就返回登陆信息不正确(code == 100就是异常情况)
//     if (result.code == 401) {
//       res.status(401).json({ error: '登录已过期,请重新登录' })
//     } else {
//       next();
//     }
//   }
// })


//注册路由
app.use('/admin', users)
app.use('/api/message', message)
app.use('/api/article', article)
app.use('/api/class', classArt)
app.use('/api/upload', upload)
app.use('/api/image', image)

app.use('/vueShow/article', vueShowArt)
app.use('/vueShow/class', vueShowClass)
app.use('/', (req, res) => {
  res.send({ msg: '123' })
})

app.listen(3000, () => {
  console.log("服务器已启动端口号3000")
})